<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      ul,
      li {
        list-style: none;
      }

      input {
        width: 580px;
        padding-left: 20px;
        height: 40px;
        margin: 30px auto 0;
        outline: none;
        display: block;
      }

      ul {
        width: 600px;
        margin: 0 auto;
        border: 1px solid #333;
        display: none;
      }

      li {
        margin: 5px 0;
      }
    </style>
  </head>

  <body>
    <!-- 搜索框 -->
    <input type="text" id="ipSearch" />

    <!-- 显示推荐信息 -->
    <ul id="ulContainer"></ul>

    <script>
      /* 部署JSONP的回调函数 */
      function fn(dataObj) {
        console.log(dataObj);
        let { g } = dataObj;
        console.log("g=", g);

        if (g) {
          //   let html = "";
          //   g.forEach((item) => {
          //     let { q } = item;
          //     console.log("q=", q);
          //     // 针对json对象中的g对象中的每个item的q 创建一个Li
          //     html += `<li>${q}</li>`;
          //   });
          //   //一堆Li丢给ul做innerHTML
          //   ulContainer.innerHTML = html;

          /* 将g数组映射为一个Li的数组 */
          ulContainer.innerHTML = g.map(
              // item进去 li出来
              ({ q }) => `<li>${q}</li>`
            ).join("");

          ulContainer.style.display = "block";
        } else {
          // 没有推荐内容藏起Ul
          ulContainer.style.display = "none";
        }

        // 删除已经用完的script标签（卸磨杀驴）
        document.querySelectorAll(".jsonp").forEach((sc) => sc.remove());
      }
    </script>

    <!-- <script src="https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36839,36548,36755,36726,36455,36413,36692,36166,36816,36570,36779,36772,36636,36745,36761,36768,36764,26350&wd=a&req=2&csor=1&cb=fn&_=1658392348948"></script> -->

    <!-- https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36839,36548,36755,36726,36455,36413,36692,36166,36816,36570,36779,36772,36636,36745,36761,36768,36764,26350&wd=a&req=2&csor=1&cb=jQuery110209519268984138005_1658392348937&_=1658392348948 -->
    <script>
      // 用户输入一改变（input事件）
      ipSearch.oninput = function (e) {
        /* 发起JSONP请求 */
        // 动态造一个script标签
        const sc = document.createElement("script");
        sc.className = "jsonp";

        // 设置其src中的wd查询参数修改为用户的输入
        sc.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36839,36548,36755,36726,36455,36413,36692,36166,36816,36570,36779,36772,36636,36745,36761,36768,36764,26350&wd=${ipSearch.value}&req=2&csor=1&cb=fn&_=1658392348948`;

        // 将script标签丢在页面上（立刻工作）
        document.body.appendChild(sc);
      };
    </script>
  </body>
</html>
